<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<h1>监听测试页面-司机客户端</h1>
<div id="app">
  <!--  <label for="content">发送消息</label>-->
  <!--  <input id="content" type="text" v-model="content">-->
  <!--  <button @click="handleSendMsg">点击发送消息</button>-->
  <button @click="closeConnection">关闭连接</button>
  <div>
    消息内容:
    <ul>
      <li v-for="(item, index) in messages" :key="index">
        {{item}}
      </li>
    </ul>
  </div>
</div>
</body>
</html>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="module">
  import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'

  const sseUrl = 'http://localhost:9000/connect'
  const closeUrl = 'http://localhost:9000/close'
  const userId = '1'
  const identity = 2

  createApp({
    data() {
      return {
        messages: [],
        source: {}
      }
    },
    methods: {
      handleSendMsg(content) {
        this.messages.push(content)
      },
      closeConnection() {
        console.log('调用close方法')
        this.source.close()
        const httpRequest = new XMLHttpRequest()
        httpRequest.open('GET', closeUrl + userId)
        httpRequest.send()
      }
    },
    created() {
      if (window.EventSource) {
        console.log('此浏览器支持SSE')

        const map = new Map()
        map.set('userId', userId).set('identity', identity)
        const api = createQueryParameters(sseUrl, map)

        this.source = new EventSource(api)
        this.source.addEventListener('message', e => {
          const content = e.data
          console.info(`消息内容: ${content}`)
          this.handleSendMsg(content)
        })
      } else {
        this.handleSendMsg('浏览器不支持SSE')
      }
    }
  }).mount('#app')

  /**
   * 拼接查询参数
   * @param api  基准api
   * @param conditions  封装了查询条件的Map对象
   * @returns {*}
   */
  function createQueryParameters(api, conditions) {
    const arr = []
    for (let entry of conditions.entries()) {
      const condition = entry.join('=')
      arr.push(condition)
    }
    const params = arr.join('&')
    return api.concat('?', params)
  }
</script>